package manager

import (
	"encoding/json"
	"github.com/cihub/seelog"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"os"
	"strconv"
)

type FinishMessage struct {
	Name   string
	Status string
}

const (
	FINISH_TOPIC = "file_transfer_finish"
)

var AIFinishHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
	seelog.Infof("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
	msgFinish := FinishMessage{}
	err := json.Unmarshal(msg.Payload(), &msgFinish)
	if err != nil {
		seelog.Errorf("Unmarshal message failed: %s", err.Error())
	}
}

func Publish(client mqtt.Client, msg *FinishMessage) {
	message, err := json.Marshal(msg)
	if err != nil {
		seelog.Errorf("Marshal message failed: %s", err.Error())
	}

	byteValue := 1
	qos := os.Getenv("MQTT_QOS")
	byteValue, err = strconv.Atoi(qos)
	if err != nil {
		seelog.Errorf("转换出错: %v\n", err)
	}

	or := client.OptionsReader()
	server := or.Servers()
	seelog.Infof("Publishing message: %s to topic: %s with qos: %d server: %v\n", string(message), FINISH_TOPIC, byteValue, server)
	token := client.Publish(FINISH_TOPIC, byte(byteValue), false, string(message))
	token.Wait()
}
